module MyList exposing (..)
import Html exposing (Html, a, button, code, div, h1, li, text, ul, br,input)
import Http
import Json.Decode as Decode

type Model =
 Model (List Node) Log

type Msg = 
 GetListResult (Result Http.Error (Result String (List Node)))

type Node = Node Id Title IsArticle  


type alias Log = String
type alias Id = String
type alias Title = String
type alias IsArticle = Bool 

nodeListDecoder : Decode.Decoder (List Node)
nodeListDecoder =
 let 
  nodeDecoder = Decode.map3 Node (Decode.field "id" Decode.string) (Decode.field "title" Decode.string) (Decode.field "isArticle" Decode.bool) 
 in 
  Decode.list nodeDecoder

initModel : Model
initModel = Model [] ""

enterRoute : Model -> (Model,Cmd Msg)
enterRoute ((Model nodeList log) as model) =
 let
  url = "/list/0"
  body = Http.emptyBody
  errDecoder = Decode.map Err (Decode.field "err" Decode.string)
  okDecoder = Decode.map Ok (Decode.field "ok" nodeListDecoder)
  decoder = Decode.oneOf [errDecoder,okDecoder]
  request = Http.post url body decoder
 in
  (Model nodeList "触发了routeChange", Http.send GetListResult request)

update : Msg -> Model -> (Model,Cmd Msg)
update msg (Model nodeList log) =
 case msg of
  GetListResult (Err _) ->
   (Model nodeList "获取列表失败",Cmd.none)
  GetListResult (Ok res) ->
   (Model nodeList "获取列表成功",Cmd.none)



view : Model -> Html Msg
view (Model nodeList log) =
 div []
  [ nodeListView nodeList
  , text ("Logger: " ++ log)]

nodeToString : Node -> String
nodeToString (Node id title isArticle) = 
 "id: " ++ id ++ " title: " ++ title ++ "isArticle: " ++ (toString isArticle)

nodeListView : List Node -> Html Msg
nodeListView nodeList =
 let 
  divs = List.map (\node -> div [] [text (nodeToString node)]) nodeList
 in 
  div [] divs